package com.longge;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-06-05 00:36
 */
public class MaxSumBST {

    private int ans = 0;

    public int maxSumBST(TreeNode root) {

        ergodic(root);
        return ans;
    }

    private int[] ergodic(TreeNode root) {
        if (root == null) return new int[0];
        int[] L = ergodic(root.left);
        int[] R = ergodic(root.right);
        // 左右树必须都是BST才行
        if (L == null || R == null) return null;
        int min = root.val, max = root.val, sum = root.val;
        if (L.length == 3) {
            // 当前val必须大于左树的最大值
            if (root.val <= L[1]) return null;
            min = L[0];// 最小值更新为左树最小值
            sum += L[2];
        }
        if (R.length == 3) {
            // 当前val必须小于右树的最小值
            if (root.val >= R[0]) return null;
            max = R[1];// 最大值更新为右树最大值
            sum += R[2];
        }
        ans = Math.max(ans, sum);
        return new int[]{min, max, sum};
    }




}
